//
//  TeachController.m
//  Coach_HaiGeEr
//
//  Created by liuchen on 2018/9/12.
//  Copyright © 2018年 海格尔. All rights reserved.
//

#import "TeachController.h"
#import "WKWebController.h"
#import "SDCycleScrollView.h"
#import "MineNewsController.h"
#import "JFCityViewController.h"
#import "TrainManageController.h"
#import "ExaminaColumnController.h"
#import "TeachManagementController.h"
#import "TeachSignerMessageController.h"
#import "TeachSignerCalendarController.h"
#import "TeachSimulationController.h"

#import "TeachBottomView.h"
#import "TeachActionsView.h"


@interface TeachController ()<JFCityViewControllerDelegate,SDCycleScrollViewDelegate,TeachActionsViewDelegate,TeachBottomViewDelegate>
@property (nonatomic,copy) NSArray *circleArr;
@property (nonatomic,strong) NSMutableArray *imgArr;
@property (nonatomic,strong) UIView *cycleBackView;
@property (nonatomic,strong) UIButton *leftNavButton;
@property (nonatomic,strong) SDCycleScrollView *cycleScrollView;
@property (nonatomic,strong) TeachActionsView *teachActionsView;
@property (nonatomic,strong) TeachBottomView *teachBottomView;
@property (nonatomic,weak) UILabel *newsLabel;
@property (nonatomic,copy) NSString *messageNum;
@end


@implementation TeachController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[CoachTabBarController shareLZHTabbarController].tabBar setHidden:NO];
    [self loadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createSubViews];
    [self loginByNotification];
    [self addLocation];
}

#pragma mark ==========获取数据==========
- (void)loadData{
    [self showLoading];
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_enter(group);
    dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //轮播图
        NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
        [dic setValue:[NSNumber numberWithInteger:1] forKey:@"page"];
        [dic setValue:[NSNumber numberWithInteger:10] forKey:@"size"];
        [dic setValue:[NSNumber numberWithInteger:1] forKey:@"contentType"];
        [dic setValue:@"2" forKey:@"targetClient"];
        [dic setValue:@"999999" forKey:@"targetArea"];
        [dic setValue:@"" forKey:@"targetSubject"];
        [dic setValue:@"" forKey:@"targetCartype"];
        [[NetworkEngine sharedClient] GETByToken:CIRCLEPICTURE data:dic success:^(id responseObject) {
            if ([[responseObject objectForKey:@"code"] integerValue]==1) {
                if ([[responseObject objectForKey:@"data"] isKindOfClass:[NSArray class]]) {
                    self.circleArr = [responseObject objectForKey:@"data"];
                    self.imgArr = [self returnArray:[responseObject objectForKey:@"data"]];
                }
            } else if ([[responseObject objectForKey:@"code"] integerValue]==1){
                [self hideHUD];
                [self toLoginVC];
            }
            dispatch_group_leave(group);
        } failure:^(NSString *error) {
            [self showError:@"加载失败"];
            dispatch_group_leave(group);
        }];
    });
    dispatch_group_enter(group);
    dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [[NetworkEngine sharedClient] GETByToken:NOREADMESSAGE data:nil success:^(id responseObject) {
            if ([[responseObject objectForKey:@"code"] integerValue]==1) {
                if ([responseObject isKindOfClass:[NSDictionary class]]) {
                    NSInteger number = [[responseObject objectForKey:@"data"] integerValue];
                    self.newsLabel.hidden = NO;
                    if (number > 99) {
                        self.messageNum = @"99+";
                    }else if (number == 0) {
                        self.messageNum = @"0";
                    }else {
                        self.messageNum = [NSString stringWithFormat:@"%ld", number];
                    }
                }
            } else if ([[responseObject objectForKey:@"code"] integerValue]==1){
                [self hideHUD];
                [self toLoginVC];
            }
            dispatch_group_leave(group);
        } failure:^(NSString *error) {
            [self showError:error];
            dispatch_group_leave(group);
        }];
    });
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        [self hideHUD];
        //界面刷新
        [self.teachBottomView loadData];
        self.cycleScrollView.imageURLStringsGroup = self.imgArr;
        self.newsLabel.text = self.messageNum;
        if (![self.messageNum integerValue]) {
            self.newsLabel.hidden = YES;
        }
    });
}

#pragma mark ==========创建视图==========
- (void)createSubViews{
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"教学";
    [self setNavRightBarButton:CGRectMake(0, 0, 100*SCALEUNIT, 40*SCALEUNIT) title:@"定位中" action:@selector(cityChange:) normalImage:nil highlightImage:nil WithJudge:NO];
    
    CGRect tempFrame = CGRectMake(0, 0, 25*SCALING, 25*SCALING);
    UIButton *tempButton = [[UIButton alloc] initWithFrame:tempFrame];
    [tempButton addTarget:self
                   action:@selector(jumopToMessagePage)
         forControlEvents:UIControlEventTouchUpInside];
    [tempButton setImage:[UIImage imageNamed:@"TeachMessageImg"]
                forState:UIControlStateNormal];
    CGRect newsFrame = CGRectMake(15 * SCALING, -10 * SCALING, 15 * SCALING, 15 * SCALING);
    UILabel *newsLabel = [[UILabel alloc] initWithFrame:newsFrame];
    [newsLabel setFont:[UIFont systemFontOfSize:11.0f * SCALING]];
    [newsLabel setTextAlignment:NSTextAlignmentCenter];
    [newsLabel setAdjustsFontSizeToFitWidth:YES];
    [newsLabel setTextColor:[UIColor whiteColor]];
    [newsLabel setBackgroundColor:[UIColor redColor]];
    newsLabel.layer.masksToBounds = YES;
    newsLabel.layer.cornerRadius = 15*SCALING*0.5;
    newsLabel.hidden = YES;
    _newsLabel = newsLabel;
    [tempButton addSubview:self.newsLabel];
    UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithCustomView:tempButton];
    self.navigationItem.rightBarButtonItem = rightBarButton;
    
    [self.view addSubview:self.cycleBackView];
    
    [self.view addSubview:self.teachActionsView];
    
    [self.view addSubview:self.teachBottomView];
}

#pragma mark ==========懒加载==========
- (UIView *)cycleBackView{
    if (!_cycleBackView) {
        _cycleBackView = [[UIView alloc] initWithFrame:CGRectMake(0, SYSTEM_TOP, SCREEN_WIDTH, 265*SCALEUNIT)];
        _cycleBackView.backgroundColor = [UIColor colorWithHexString:@"#eeeeee"];
        [_cycleBackView addSubview:self.cycleScrollView];
    }
    return _cycleBackView;
}
- (SDCycleScrollView *)cycleScrollView{
    if (!_cycleScrollView) {
        _cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(20*SCALEUNIT, 15*SCALEUNIT, SCREEN_WIDTH-20*SCALEUNIT*2, 265*SCALEUNIT-15*SCALEUNIT*2) delegate:self placeholderImage:[UIImage imageNamed:@"TeachSeizePlaceImg"]];
        _cycleScrollView.showPageControl = YES;
        _cycleScrollView.localizationImageNamesGroup = @[@"TeachSeizePlaceImg",@"TeachSeizePlaceImg",@"TeachSeizePlaceImg"];
        _cycleScrollView.delegate = self;
    }
    return _cycleScrollView;
}
- (TeachActionsView *)teachActionsView{
    if (!_teachActionsView) {
        _teachActionsView = [[TeachActionsView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.cycleBackView.frame), SCREEN_WIDTH, 185*SCALEUNIT)];
        _teachActionsView.delegate = self;
    }
    return _teachActionsView;
}
- (TeachBottomView *)teachBottomView{
    if (!_teachBottomView) {
        _teachBottomView = [[TeachBottomView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.teachActionsView.frame), SCREEN_WIDTH, SCREEN_HEIGHT-CGRectGetMaxY(self.teachActionsView.frame)-[CoachTabBarController shareLZHTabbarController].tabBar.frame.size.height)];
        _teachBottomView.delegate = self;
    }
    return _teachBottomView;
}
- (NSMutableArray *)imgArr{
    if (!_imgArr) {
        _imgArr = [[NSMutableArray alloc]init];
    }
    return _imgArr;
}

#pragma mark ==========更换城市==========
- (void)cityChange:(UIButton *)btn{
    JFCityViewController *cityViewController = [[JFCityViewController alloc] init];
    //设置代理
    cityViewController.delegate = self;
    cityViewController.title = @"城市";
    //给JFCityViewController添加一个导航控制器
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:cityViewController];
    [self presentViewController:navigationController animated:YES completion:nil];
}
- (void)addLocation{
    WS(ws);
    [[LocationService shareInstance] openLocationWithBlock:^(NSString *city, NSString *adCode) {
        [UserMessage sharedInstance].model.currentCity = city;
        [UserMessage sharedInstance].model.currentAdCode = adCode;
        ws.leftNavButton = (UIButton *)ws.navigationItem.leftBarButtonItem.customView;
        [ws.leftNavButton setTitle:[[[UserMessage sharedInstance].model.currentCity componentsSeparatedByString:@"市"] firstObject] forState:UIControlStateNormal];
    }];
}
- (void)cityName:(NSString *)name {
    [self.leftNavButton setTitle:[[name componentsSeparatedByString:@"市"] firstObject] forState:UIControlStateNormal];
}

#pragma mark ==========TeachActionsViewDelegate代理==========
- (void)teachActionsViewDelegateWithTag:(NSInteger)tagNum{
    switch (tagNum) {
        case 0:{
            [self.navigationController pushViewController:[[TeachManagementController alloc]init] animated:YES];
        }
            break;
        case 1:{
            [self.navigationController pushViewController:[[TrainManageController
                                                            alloc]init] animated:YES];
        }
            break;
        case 2:{
            [self.navigationController pushViewController:[TeachSimulationController new] animated:YES];
        }
            break;
        case 3:{
            [self.navigationController pushViewController:[ExaminaColumnController new] animated:YES];
        }
            break;
        default:
            break;
    }
}

#pragma mark ==========TeachBottomViewDelegate代理==========
- (void)teachBottomViewDelegateToVCWithJudge:(NSInteger)judge{
    if (judge==1) {
        [self hideHUD];
        [self toLoginVC];
    } else if (judge==2) {
        TeachSignerCalendarController *canlendarVC = [[TeachSignerCalendarController alloc] init];
        WS(ws);
        canlendarVC.block = ^(NSDate *date) {
            if (date!=nil) {
                [ws.teachBottomView changeTimeWithDate:date];
            }
        };
        [self.navigationController pushViewController:canlendarVC animated:YES];
    } else {}
}
- (void)teachBottomViewDelegateToSingerVCWithIds:(NSNumber *)ids WithSubjectType:(NSNumber *)subjectType WithCurrentDate:(NSString *)currentDate{
    TeachSignerMessageController *signerVC = [[TeachSignerMessageController alloc] init];
    signerVC.ids = ids;
    signerVC.subjectType = subjectType;
    signerVC.currentDate = currentDate;
    [self.navigationController pushViewController:signerVC animated:YES];
}

#pragma mark ==========SDCycleScrollViewDelegate代理==========
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index{
    WKWebController *wkWeb = [[WKWebController alloc]init];
    wkWeb.titleConten = [[self.circleArr objectAtIndex:index] objectForKey:@"title"];
    wkWeb.url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@%@",NETWORK_URL,CIRCLEDETAIL,[[self.circleArr objectAtIndex:index] objectForKey:@"id"]]];
    [self.navigationController pushViewController:wkWeb animated:YES];
}

#pragma mark ==========跳转到我的消息==========
- (void)jumopToMessagePage{
    self.newsLabel.text = @"";
    [self.navigationController pushViewController:[[MineNewsController alloc] init] animated:YES];
}

#pragma mark ==========从轮播数据中筛选出图片url==========
- (NSMutableArray *)returnArray:(NSArray *)arr{
    NSMutableArray *imgArr = [[NSMutableArray alloc] init];
    for (int i=0; i<arr.count; i++) {
        [imgArr addObject:[[arr objectAtIndex:i] objectForKey:@"slideshowId"]];
    }
    return imgArr;
}

#pragma mark ==========点击推送进入判断==========
- (void)loginByNotification{
    if ([UserMessage sharedInstance].model.loginType == 1) {
        [UserMessage sharedInstance].model.loginType = 0;
        [self.navigationController pushViewController:[[MineNewsController alloc] init] animated:YES];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
